package com.longrise.android.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;


public class EnCryptDeCrypt {
    private String key;
    private SecretKeyFactory keyFactory;
    private DESKeySpec desKeySpec;
    private static SecretKey secretKey;
    private static IvParameterSpec iv;
    private static Cipher cipher;
    private static EnCryptDeCrypt mEnCryptDeCrypt = null;

    public static EnCryptDeCrypt getInstance() {
        if (mEnCryptDeCrypt == null) {
            synchronized (EnCryptDeCrypt.class) {
                if (mEnCryptDeCrypt == null) {
                    mEnCryptDeCrypt = new EnCryptDeCrypt();
                }
            }
        }
        return mEnCryptDeCrypt;
    }

    public EnCryptDeCrypt() {
        String key = "s(p7~;j^";
        new EnCryptDeCrypt(key);
    }

    public EnCryptDeCrypt(String cuskey) {
        try {
            key = cuskey;
            cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
            keyFactory = SecretKeyFactory.getInstance("DES");
            secretKey = keyFactory.generateSecret(desKeySpec);
            iv = new IvParameterSpec(key.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 加密
    public String EnCrypt(String message) throws Exception {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte data[] = message.getBytes("UTF-8");
            System.out.println(data.toString());
            byte[] encryptedData = cipher.doFinal(data);
            System.out.println(encryptedData.toString());
            BASE64Encoder decoder = new BASE64Encoder();
            String sss = decoder.encode(encryptedData);
            System.out.print(sss);
            return sss;
        } catch (Exception e) {
            return null;
        }
    }

    // 解密
    public String deCrypt(String message) throws Exception {
        try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte data[] = getFromBASE64(message);
            byte[] encryptedData = cipher.doFinal(data);
            return new String(encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    private byte[] getFromBASE64(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return b;
        } catch (Exception e) {
            return null;
        }
    }

//	public native String getDesEncryptionStr();

//	static {
//		System.loadLibrary("EnCryptDeCrypt");// 加载库，前面的lib和，后缀名不用写
//	}

}
